using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rb; // 刚体组件
    public float speed, jumpForce; // 移动速度和跳跃力度
    public Transform groundCheck; // 地面检测点
    public LayerMask ground; // 地面图层
    public bool isGround; // 是否在地面上
    bool jumpPressed; // 是否按下跳跃键

    //检测范围
    public float checkRadius;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>(); // 获取刚体组件
    }

    void Update()
    {
        if (Input.GetButtonDown("Jump"))
        {
            jumpPressed = true;
        }

    }

    private void FixedUpdate()
    {
        isGround = Physics2D.OverlapCircle(groundCheck.position, checkRadius, ground); // 检测是否在地面上
        GroundMovement(); // 地面移动
        Jump(); // 跳跃
    }

    //画出的射线可以看见
    private void OnDrawGizmosSelected()
    {
        if (groundCheck != null)
        {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(groundCheck.position, checkRadius);
        }

    }

    void GroundMovement()
    {
        float horizontal = Input.GetAxisRaw("Horizontal"); // 获取水平方向输入
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y); // 设置刚体速度
        if (horizontal != 0)
        {
            transform.localScale = new Vector3(horizontal, 1, 1); // 翻转角色
        }
    }

    void Jump()
    {
        if (jumpPressed && isGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce); // 设置刚体速度
            jumpPressed = false;
        }
    }
}
